/******************************************************************************
 *
 *  socket_tcp_fork_server.c
 *
 *  Created on: 2012-3-11
 *      Author: Michael
 *       Email: zhongchao.ustc@gmail.com
 *
 *  Copyright (c) Michael Chao Zhong
 *
 *****************************************************************************/

#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
	// Create Socket
	int socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
	
	// Bind
	struct sockaddr_in server_addr;
	bzero(&server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = INADDR_ANY;
	server_addr.sin_port = htons(atoi(argv[1]));
	bind(socket_fd, (struct sockaddr *) &server_addr, sizeof(server_addr));

	// As accept
	while (1)
	{
		// Receive and write
		char buffer[1024];
		struct sockaddr_in client_addr;
		socklen_t client_addr_length = sizeof(client_addr);
		int msg_recv_length = recvfrom(socket_fd, buffer, sizeof(buffer), 0,
				(struct sockaddr *) &client_addr, &client_addr_length);
		const char *hint = "Received a datagram: ";
		write(1, hint, strlen(hint));
		write(1, buffer, msg_recv_length);

		// Send
		const char *msg_send = "Got your message\n";
		sendto(socket_fd, msg_send, strlen(msg_send), 0,
				(struct sockaddr *) &client_addr, sizeof(struct sockaddr_in));
	}

	// Close
	close(socket_fd);

	return 0;
}
